/**
拷贝如下代码到列表页，原因：该页面的确认事件是回调执行的

//事件-新增（选人）
window.onAddByCallback = function (selectedObjs, selectedIds) {
    let list = selectedObjs.map(v=>{
        delete v.id
        return v
    })
    var opts = {
        data: list
    }
    exutil.post('/api/black/user/add', opts).then(function (res) {
        exutil.toast("操作成功");
        exutil.updateTabTable(table.tag);//不能使用this或that，因为window.onAddByCallback已经指向顶级
        exutil.close();
    });
}

 */

layui.use(['jquery', 'laytpl', 'extable', 'form', 'sysOrganization'],
    function () {
        var $ = layui.$;
        var extable = layui.extable;
        var form = layui.form;
        var laytpl = layui.laytpl;
        var exutil = layui.exutil;
        var sysOrganization = layui.sysOrganization;

        //表格接口
        var tableAPI = '/api/black/user/selectList';

        var elms = {
            elmSelectArea: $(".wt-selected-area"),
            submitBtn: $('button[lay-filter="save"]'),
            oOrgTree: $('#org_tree'),
            tplSelectItem: $('#select_item'),
            tplBatchSelectItem: $('#batch_select_item')
        };

        var datas = {
            tableCurrentPage: 1,
            isOnly: exutil.getUrlParam('isOnly') === "true" ? true : false,
            sourceType: exutil.getUrlParam('sourceType'), //来源类型 必填  可填值‘tab’,'win'
            sourceIndex: exutil.getUrlParam('sourceIndex'), //来源Index 选填
            callBack: exutil.getUrlParam('callBack'), //回调方法 必填
            isSelectAll: exutil.getUrlParam('isSelectAll') || 'part',  //可选人员 选填 所有人员选择'all'  部分人员选择'part'(默认)
            noUserTips: exutil.getUrlParam('noUserTips') || '请选择所属用户',
            selectedOrg: null,
            selectedUsers: [],
            selectedUserIds: [],
            belongUserTable: null,
            searchCondition: {
                orgId: '',
                personnelType: '0' //固定人员
            },
        };

        var methods = {
            initOrgTree: function (params) {
                var that = this;
                sysOrganization.getTree({
                    data: params || {}
                }).then(function (res) {
                    if (res && res.length > 0) {
                        // 处理组织树数据
                        if (params == null || params.name === '') {
                            res.unshift({
                                name: '全部',
                                rid: ''
                            })
                        }
                        elms.oOrgTree.tree({
                            data: res,
                            lines: true,
                            formatter: function (node) {
                                return node.name;
                            },
                            onSelect: function (e) {
                                if (!datas.selectedOrg || e.id !== datas.selectedOrg.id) {
                                    datas.selectedOrg = e;
                                    datas.searchCondition.orgId = e.rid
                                    that.initMainTable(datas.searchCondition);
                                }
                            },
                            onLoadSuccess: function (node, data) {
                                if (data.length === 0) {
                                    return;
                                }
                                // 查找第一个元素
                                var n = elms.oOrgTree.tree('find', data[0].id);
                                if (data.length === 1) {
                                    elms.oOrgTree.tree("collapseAll").tree('expand', n.target);
                                } else {
                                    elms.oOrgTree.tree("collapseAll")
                                }
                                // 选择第一个元素
                                elms.oOrgTree.tree('select', n.target);
                            }
                        });
                        // 删除tree图标
                        that.delTreeIcon();

                    } else {
                        that.initMainTable();
                        elms.oOrgTree.html('- 暂无组织机构数据 -')
                    }

                });
            },
            delTreeIcon: function () {
                elms.oOrgTree.find("span.tree-icon").removeClass('tree-folder tree-file');
            },
            // 初始化员工列表
            initMainTable: function (d) {
                var where = {};
                where.orgId = (d && d.orgId !== "") ? d.orgId : null;
                where.personnelType = d.personnelType
                if (datas.belongUserTable) {
                    extable.reload('belongUserTable', {
                        where: where
                    });
                } else {
                    var cols = [
                        {
                            field: 'personnelNo',
                            title: '人员编号',
                            width: 160
                        },
                        {
                            field: 'personnelName',//'userName',
                            title: '用户名',
                            width: 120
                        }, {
                            field: 'idNo',
                            title: '身份证',
                            width: 200
                        },
                        {
                            field: 'orgName',//'department',
                            title: '组织机构',
                            minWidth: '300'
                        },
                        {
                            fixed: 'right',
                            title: '操作',
                            toolbar: '#rowbar',
                            width: 70
                        }
                    ];

                    var toolbar = false;

                    // 非单选
                    if (!datas.isOnly) {
                        toolbar = '#toolbar';
                        cols.unshift({
                            type: 'checkbox'
                        })
                    }


                    datas.belongUserTable = extable.render({
                        elem: '#belongUserTable',
                        url: tableAPI,
                        height: 'full-78',
                        where: where,
                        id: 'belongUserTable',
                        page: true,
                        loading: true,
                        toolbar: toolbar,
                        defaultToolbar: ['filter'],
                        cols: [cols],
                        done: function (res, curr, count) {
                            // 设置当前页码
                            datas.tableCurrentPage = curr;
                        }
                    });
                }
            },
            selectUser: function (userInfo) {

                if ($.inArray(userInfo.id, datas.selectedUserIds) == -1) {
                    datas.selectedUserIds.push(String(userInfo.id));
                    datas.selectedUsers.push(userInfo);
                    laytpl(elms.tplSelectItem.html()).render(userInfo, function (html) {
                        elms.elmSelectArea.append(html);
                    });

                } else {
                    exutil.toast("已选择");
                }
            },
            removeSelectedItemsById: function (id) {
                var i = $.inArray(id, datas.selectedUserIds);

                if (i !== -1) {
                    datas.selectedUserIds.splice(i, 1);
                    datas.selectedUsers.splice(i, 1);
                }
            },
            batchSelectUser: function (users) {
                var count = users.length,
                    showUsers = [];
                for (var i = 0; i < count; i++) {
                    if ($.inArray(users[i].id, datas.selectedUserIds) == -1) {
                        datas.selectedUserIds.push(String(users[i].id));
                        datas.selectedUsers.push(users[i]);
                        showUsers.push(users[i])
                    }
                }

                if (showUsers.length > 0) {
                    laytpl(elms.tplBatchSelectItem.html()).render(showUsers, function (html) {
                        elms.elmSelectArea.append(html);
                    });
                } else {
                    exutil.toast("已选择");
                }

            },
            // 提交
            _saveForm: function () {

                if (datas.selectedUserIds.length === 0) {
                    exutil.toast(datas.noUserTips);
                    return;
                }

                if (datas.sourceType === "tab") {
                    if (datas.sourceIndex) {
                        // 来自非当前tab
                        var sourceWin = $('iframe[data-key="' + datas.sourceIndex + '"]', top.document)[0].contentWindow;
                        sourceWin[datas.callBack](datas.selectedUsers, datas.selectedUserIds);
                    } else {
                        // 来自当前tab
                        var currentTabId = top.layui.exconfig.currentShowMenuKey.join(),
                            currentTabWin = $('iframe[data-key="' + currentTabId + '"]', top.document)[0].contentWindow;
                        currentTabWin[datas.callBack](datas.selectedUsers, datas.selectedUserIds);
                    }
                } else if (datas.sourceType === "win") {
                    if (datas.sourceIndex) {
                        // 来自指定win
                        var winSize = top.layui.exconfig.wins.length;
                        for (var i = 0; i < winSize; i++) {
                            if (datas.sourceIndex === top.layui.exconfig.wins[i].index) {
                                var win = top.layui.exconfig.wins[i].ifrm.contentWindow;
                                win[datas.callBack](datas.selectedUsers, datas.selectedUserIds);
                                break;
                            }
                        }
                    } else {
                        // 来自之前win
                        var winSize = top.layui.exconfig.wins.length,
                            currentWin = top.layui.exconfig.wins[winSize - 2].ifrm.contentWindow;
                        currentWin[datas.callBack](datas.selectedUsers, datas.selectedUserIds);
                    }
                } else if (datas.sourceType === "self") {
                    top[datas.callBack](datas.selectedUsers, datas.selectedUserIds);
                }

            },
            // 重置
            _clearAll: function () {
                elms.elmSelectArea.empty();
                datas.selectedUsers = [];
                datas.selectedUserIds = [];
                return false;
            }

        };

        window._yesRun = methods._saveForm;
        window._btn2Run = methods._clearAll;
        methods.initOrgTree();


        /**
         * 事件处理
         */
        extable.on('tool(belongUserTable)', function (obj) {
            var data = obj.data,
                layEvent = obj.event,
                tr = obj.tr;

            if (layEvent === 'detail') {

            } else if (layEvent === 'sel') {
                if (datas.isOnly && datas.selectedUserIds.length > 0) {
                    exutil.toast("不支持多选");
                } else {
                    methods.selectUser(data);
                }

            }
        });

        extable.on('toolbar(belongUserTable)', function (obj) {

            var checkStatus = extable.checkStatus('belongUserTable'),
                size = checkStatus.data.length,
                checkData = checkStatus.data,
                res = [];

            switch (obj.event) {
                case 'batchbSel':
                    if (size === 0) {
                        exutil.toast("请选择用户");
                    } else if (datas.isOnly && datas.selectedUserIds.length > 0) {
                        exutil.toast("不支持多选");
                    } else if (datas.isOnly && size > 1) {
                        exutil.toast("不支持多选");
                    } else {
                        methods.batchSelectUser(checkData);
                    }
                    break;
            }
        });

        /**
         * 查询
         */
        form.on('submit(search)', function (data) {
            // 全局搜索
            // data.field.orgId = '';
            let where = $.extend(true, {}, datas.searchCondition, data.field);
            exutil.updateWinTable('belongUserTable', null, null, where);
            return false;
        });

        $('.wt-selected-area').on('click', '.wt-close', function (ev) {
            var id = String($(this).data('id'));
            $(this).parent().remove();
            methods.removeSelectedItemsById(id);
            ev.stopPropagation();
        });

        form.on('submit(orgSearch)', function (data) {
            methods.initOrgTree(data.field)
            return false;
        });



    });
